const mongoose = require('mongoose')
const Joi = require('joi')

const articleSchema = new mongoose.Schema(
  {
    title: {
      type: String,
      required: true,
      maxLength: 20,
      minLength: 1
    },
    content: {
      type: String,
      required: true,
      maxLength: 200,
      minLength: 10
    },
    status: String,
    createdAt: {
      type: Date,
      default: Date.now
    },
    updatedAt: {
      type: Date,
      default: Date.now
    },
    category: {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'Category',
      required: true
    },
    author: {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'User',
      required: true
    }
  },
  {
    timestamps: true
  }
)

const Article = mongoose.model('Article', articleSchema)

// 校验函数
function articlealidator(data) {
  const schema = Joi.object({
    title: Joi.string().min(2).max(50).required(),
    content: Joi.string().min(10).max(200).required(),
    status: Joi.string().valid('published').required().messages({
      'any.only': 'valid取值有误, 可选值为published'
    }),
    category: Joi.string()
  })
  return schema.validate(data)
}

module.exports = {
  Article,
  articlealidator
}
